package com.gitee.wsl.data.input.viewmodel.undo.state

import com.gitee.wsl.data.input.strategy.FifoInputStrategy
import com.gitee.wsl.data.input.viewmodel.InputModelConfiguration
import com.gitee.wsl.data.input.viewmodel.withViewModel
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.sample
import kotlin.time.Duration.Companion.seconds

@OptIn(FlowPreview::class)
public fun <Inputs : Any, Events : Any, State : Any> InputModelConfiguration.Builder.withStateBasedUndoController(
    bufferStates: (Flow<State>) -> Flow<State> = { it.sample(5.seconds) },
    historyDepth: Int = 10,
): InputModelConfiguration.TypedBuilder<
        StateBasedUndoControllerContract.Inputs<Inputs, Events, State>,
        StateBasedUndoControllerContract.Events<Inputs, Events, State>,
        StateBasedUndoControllerContract.State<Inputs, Events, State>> {
    return this
        .withViewModel(
            initialState = StateBasedUndoControllerContract.State<Inputs, Events, State>(),
            inputHandler = StateBasedUndoControllerInputHandler<Inputs, Events, State>(bufferStates, historyDepth),
            name = "UndoController",
        )
        .apply {
            this.inputStrategy = FifoInputStrategy.typed()
        }
}
